import type { AnyObject } from "@/types";
import type { FormInstance } from "element-plus";
import { isReactive, ref } from "vue";
// import { cloneDeep } from "lodash-es";

export interface UseSubmitOption {
  form: AnyObject; // 表单
  ajax: () => Promise<any>; // 提交函数
}

export function useSubmit(option: UseSubmitOption) {

  const { form, ajax } = option;
  
  if(!isReactive(form)) {
    throw new Error('form必须是reactive类型');
  }

  // 表单备份
  // const backupForm = cloneDeep(form);

  // 加载中
  const loading = ref(false);

  // 表单ref
  const formRef = ref<FormInstance>();

  // 提交表单
  const submit = () => {
    // 校验
    return new Promise<void>((resolve, reject) => {
      if (!formRef.value) {
        reject(new Error('formRef未绑定'));
        return;
      }
      formRef.value!.validate(async (valid, fields) => {
        if (valid) {
          // 提交
          loading.value = true;
          try {
            await ajax();
            // 重置
            // reset(); // 自动重置会有一些界面闪烁问题
            resolve();
          } catch(error) {
            reject(error);
          } finally {
            loading.value = false;
          }
        }
      });
    });
  };

  // 重置表单
  const reset = () => {
    // for (const prop in backupForm) {
    //   form[prop] = cloneDeep(backupForm[prop]);
    // }
    formRef.value?.resetFields();
    
  };

  // 清除校验状态
  const clear = () => {
    formRef.value?.clearValidate();
  };

  return {
    loading, submit, reset, formRef, clear
  }
}